// TODO Promise的特点

//? 1）里面有三个状态 等待态（默认） 成功态  失败态  一旦成功了就不能失败，反过来页一样
//? resolve 代表的是成功  reject代表的是失败
//? 2） 每个promise实力都有一个then方法
// ? 3）如果new Promise的时候 报错了，会变成失败态  （抛错）


const PENDING = 'PENDING';
const RESOLVED = 'RESOLVED';
const REJECTED = 'REJECTED';

class MyPromise {
  // 1.看
  #status = PENDING;
  #value = undefined;
  #reason = undefined;
  #onResolvedCallbacks = [];
  #onRejectedCallbacks = [];
  constructor(executor) {
    //* 成功函数 
    let resolve = (value) => {
      if (this.#status === PENDING) {
        this.#status = RESOLVED;
        this.#value = value;
        this.#onResolvedCallbacks.forEach(fn => fn())
      }
    }
    //* 失败函数 
    let reject = (reason) => {
      if (this.#status === PENDING) {
        this.#status = REJECTED;
        this.#reason = reason;
        this.#onRejectedCallbacks.forEach(fn => fn())
      }
    }
    try {
      executor(resolve, reject)
    } catch (error) { //!如果执行过程中报错了，执行reject
      reject(error)
    }
  }
  // TODO then方法的实现 
  then(onfullfield, onrejected) { //?then有两个参数
    if (this.#status === RESOLVED) {
      onfullfield(this.#value)
    }
    if (this.#status === REJECTED) {
      onrejected(this.#reason)
    }
    //! 如果是异步 先订阅 
    if (this.#status === PENDING) {
      this.#onResolvedCallbacks.push(() => {
        onfullfield(this.#value);
      })
      this.#onRejectedCallbacks.push(() => {
        onrejected(this.#value);
      })
    }
  }
  // TODO catch方法的实现
  catch(err) {

  }
}

/* let p1 = new MyPromise((resolve, reject) => {
  console.log(111);
  setTimeout(() => {
    resolve('fuck');
  }, 2000);
})
 */